from flask import Flask, render_template,request,jsonify
import json
import os
import time
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
import base64
from sys_info import get_sys_info
from raspi_car import MyCar



testInfo={}

app = Flask(__name__)
mycar = MyCar()
mycar.listenStopSignal()
mycar.listHuman()
mycar.listenDistance()
mycar.listenServoTurn()
'''
# 生成扫描距离图
@app.route('/servo/plot',methods=['GET', 'POST'])
def servo_plot():
    print("gen distance scan")
    info = {}
    x = np.array(mycar.servo_angle)
    y = np.array(mycar.servo_distance)

    plt.grid(True)
    plt.plot(x,y,'r')

    url_addr = './static/new_plot.png'

    plt.savefig(url_addr,dpi=400, bbox_inches='tight')
    plt.close()
    info['img_url'] = '/static/new_plot.png'
    return json.dumps(info)    
'''
@app.route('/servo/plot',methods=['GET', 'POST'])
def servo_plot():
    print("gen distance scan")
    info = {}

    print(mycar.servo_angle)
    print(mycar.servo_distance)

    x = np.array(mycar.servo_angle)
    y = np.array(mycar.servo_distance)

    plt.grid(True)
    plt.plot(x,y,'r')

    sio = BytesIO()
    plt.savefig(sio, format='png',bbox_inches='tight')
    plt.close()
    data = base64.encodebytes(sio.getvalue()).decode()


    img_head = "data:image/png;base64,"

    info['img_url'] = img_head+data
    return json.dumps(info)

    
# 获得系统信息
@app.route('/sys_info', methods=['GET', 'POST'])  # 路由
def sys_info():
    # 将系统信息返回的函数值赋值给变量
    testInfo = get_sys_info()
    # 计算距离开关distance_cal为真，则将距离值赋值为实际测量值
    # 为假，距离值赋值为disable
    if mycar.distance_cal:
        testInfo['front_distance']=str(int(mycar.distance_cm))+" cm"
    else:
        testInfo['front_distance']="disable"
    return json.dumps(testInfo)

# 设置小车距离感应器的状态
@app.route('/car_sensor/distance',methods=['GET','POST'])
def car_sensor_distance():
    car_distance_flag = request.form.get('dis_sensor')
    # print(car_distance_flag)
    if car_distance_flag == 'yes':
        mycar.distance_cal = True
        # print("yes",mycar.distance_cm)
    elif car_distance_flag == 'no':
        mycar.distance_cal = False
        # print('no',mycar.distance_cm)
    else:
        print('distance sensor error!')
        exit(10)
    return jsonify({'ok':True})

# 设置小车舵机的状态
@app.route('/car_sensor/servo',methods=['GET','POST'])
def car_sensor_servo():
    car_senvo_flag = request.form.get('servo_sensor')
    if car_senvo_flag == 'yes':
        mycar.servo_turn.value = 1
    elif car_senvo_flag == 'no':
        mycar.servo_turn.value = 0
    else:
        print('servo sensor error!')
        exit(10)
    return jsonify({'ok':True})




# 控制小车开始运动，前进，左右转弯
@app.route('/sys_control/start',methods=['GET','POST'])
def sys_control_start():
    car_dir = request.form.get('car_dir')
    mycar.stop_signal.value = 0
    if car_dir == 'forward':
        mycar.forward()
    elif car_dir == 'left':
        mycar.turn(1)
    elif car_dir == 'right':
        mycar.turn(-1)
    else:
        exit(3)
    return jsonify({'ok':True})

# 控制小车结束运动
@app.route('/sys_control/end',methods=['GET','POST'])
def sys_control_end():
    car_dir = request.form.get('car_dir')
    mycar.stop_signal.value = 1
    return jsonify({'ok':True})

# @app.route('/test_post/nn', methods=['GET', 'POST'])  # 路由
# def test_post():
#     testInfo['name'] = 'xiaoliao'
#     testInfo['age'] = '28'
#     return json.dumps(testInfo)

# @app.route('/test_post/mm', methods=['GET', 'POST'])  # 路由
# def get_post():
#     # testInfo['name'] = 'xiaoliao'
#     # testInfo['age'] = '28'
#     print("run ...")
#     name = request.form.get('name')
#     age= request.form.get('age')
#     # age = request.form.get('age')
#     # print(name,age)
#     print(name)
#     print(age)
#     return jsonify({'ok':True})


@app.route('/')
def hello_world():
    return 'Hello World!'

# 监控主页
@app.route('/minitor')
def index():
    return render_template('minitor.html')


if __name__=="__main__":
    app.run(
        debug=True,
        host = '0.0.0.0',
        port = 5000
        )